#pragma once

#include "stdafx.h"

#include "ISearcheableFile.h"

char* ISearcheableFile::buffer = new char[ISearcheableFile::TEN_MB];

bool ISearcheableFile::isApplicableForSearch(std::string& path)
{
	DWORD dwAttrs = GetFileAttributes(path.c_str()); 

	bool isHidden = dwAttrs & FILE_ATTRIBUTE_HIDDEN;
	bool isSystem = dwAttrs & FILE_ATTRIBUTE_SYSTEM;

	if (isHidden || isSystem)
	{
		return false;
	}

	return boost::filesystem::file_size(path) <= ISearcheableFile::TEN_MB;
}


bool ISearcheableFile::checkInWord(std::string& word, std::set<std::string>& wordSet, std::set<std::string>& foundWords)
{
	using namespace std;

	if(wordSet.count(word) == 1)
	{
		boost::algorithm::to_lower(word);
		foundWords.insert(word);
	}	

	bool searchFinished = (wordSet.size() == foundWords.size());

	return searchFinished;
}

HANDLE ISearcheableFile::openFile(std::string& fileName)
{
	HANDLE hFile = CreateFile(
		fileName.c_str(),      // file to open
		GENERIC_READ,          // open for reading
		FILE_SHARE_READ,       // share for reading
		NULL,                  // default security
		OPEN_EXISTING,         // existing file only
		FILE_FLAG_SEQUENTIAL_SCAN, // for more good buffering
		NULL);                 // no attr. template

	if (hFile == INVALID_HANDLE_VALUE) 
	{ 
		std::cout << "Couldn't open file: " << fileName << std::endl;
		return NULL; 
	} 
	else 
	{
		return hFile;
	}
}

DWORD ISearcheableFile::readInBuffer(HANDLE file, char* buffer)
{
	DWORD count = 0;

	if(FALSE == ReadFile(file, ISearcheableFile::buffer, ISearcheableFile::BUFFER_SIZE, &count, NULL))
    {        
        return 0;
	}

	return count;
}


